﻿using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace Solution
{
    /// <summary>
    /// ASP.NET WEBAPI 错误过滤
    /// </summary>
    public class ApiExceptionFilter : ExceptionFilterAttribute
    {
        #region 公共方法

        public override void OnException(HttpActionExecutedContext filterContext)
        {
            //错误信息
            string error;
            if (filterContext.Exception is ShowException)  //自定义错误
            {
                error = filterContext.Exception.Message;
            }
            else
            {
                error = ExceptionExtension.GetAllMessages(filterContext.Exception);
            }
            var result = new StandardJsonResult<dynamic>();
            result.Fail(error);

            filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Forbidden, result, "application/json");
            base.OnException(filterContext);
        }

        #endregion 公共方法
    }
}